﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Threading;

public partial class UserControl_ControlQuanLyThongTinVungDiaLy : System.Web.UI.UserControl
{
    ClassExecute.ClassExecute dt;
    string str = webapp4U.Configuration.CurrentConnectionString;
    string error = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {       
            //nằm trong thread
            ThreadStart thr = new ThreadStart(BindArea);
            ThreadStart thr1 = new ThreadStart(BindTinhThanh);

            Thread tr = new Thread(thr);
            Thread tr1 = new Thread(thr1);

            tr.Start();
            tr1.Start();

            tr.Join();
            tr1.Join();
            //nằm trong thread
            LoadTinhThanhFollowArea(DropAreaID.SelectedValue);
        }
    }

    void ShowMessageBox(string text)
    {
        MessageBox.Text = text;
        MessageBox.ShowOnPageLoad = true;
    }

    void BindArea()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getArea", CommandType.StoredProcedure);
            dt.BindDropDownList(db, DropAreaID, "RegionID", "RegionName");
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }   
    }
    protected void DropAreaID_SelectedIndexChanged(object sender, EventArgs e)
    {
        LoadTinhThanhFollowArea(DropAreaID.SelectedValue);
    }
    void LoadTinhThanhFollowArea(string areaid)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable dtListRefRegion = dt.Get_Data_DataTable(str, ref error, "TTr_RefRegion_GetListByRegionID", CommandType.StoredProcedure,
                new SqlParameter("@RegionID", areaid));
            if (dtListRefRegion.Rows.Count > 0)
            {
                ViewState["dtTinhThuocVung"] = dtListRefRegion;

                grvDsTinh.DataSource = ViewState["dtTinhThuocVung"];
              
            }
            else
            {
                grvDsTinh.DataSource = null;
            }
            grvDsTinh.DataBind(); 
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

   
    void BindTinhThanh()
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            DataTable db = dt.Get_Data_DataTable(str, ref error, "k_getTinhThanh", CommandType.StoredProcedure);
            dt.BindDropDownList(db, ddlTinhThanh, "MaTinh", "TinhThanh");
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }

    protected void grvDsTinh_RowDeleting(object sender, GridViewDeleteEventArgs e)
    {
        string keys = grvDsTinh.DataKeys[e.RowIndex].Value.ToString();

        DataTable table = new DataTable();
        table = (DataTable)ViewState["dtTinhThuocVung"];


        for (int i = 0; i < table.Rows.Count;i ++ )
        {
            if (table.Rows[i][0].ToString() == keys)
            {
                table.Rows[i].Delete();
                table.AcceptChanges();
                ViewState["dtTinhThuocVung"] = table;
                //Kiểm tra xem nếu đã xóa hết
                if (table.Rows.Count > 0)
                {
                    grvDsTinh.DataSource = ViewState["dtTinhThuocVung"];
                    grvDsTinh.DataBind();
                }
                else
                {
                    grvDsTinh.DataSource = null;
                    grvDsTinh.DataBind();
                    ViewState["dtTinhThuocVung"] = null;
                }
            }            
        }
    }

    protected void btnAdd_Click(object sender, EventArgs e)
    {
        //Add tỉnh
        DataTable dtTinh = new DataTable();
        if (ViewState["dtTinhThuocVung"] == null)
        {
            DataColumn dtc;

            //Tao Cot Ma Hang
            dtc = new DataColumn();
            dtc.DataType = Type.GetType("System.String");
            dtc.ColumnName = "MaTinh";
            dtTinh.Columns.Add(dtc);

            //Tao Cot Ten Hang
            dtc = new DataColumn();
            dtc.DataType = Type.GetType("System.String");
            dtc.ColumnName = "TinhThanh";
            dtTinh.Columns.Add(dtc);

            DataRow dr = dtTinh.NewRow();
            dr[0] = ddlTinhThanh.SelectedValue;
            dr[1] = ddlTinhThanh.SelectedItem.Text;

            dtTinh.Rows.Add(dr);
            ViewState["dtTinhThuocVung"] = dtTinh;

            grvDsTinh.DataSource = ViewState["dtTinhThuocVung"];
            grvDsTinh.DataBind();

        }
        else
        {
            dtTinh = (DataTable)ViewState["dtTinhThuocVung"];
            for (int i = 0; i < dtTinh.Rows.Count; i++)
            {
                if (ddlTinhThanh.SelectedValue == dtTinh.Rows[i]["MaTinh"].ToString())
                {
                    dtTinh.Rows.RemoveAt(i);
                    break;
                }
            }
            DataRow dr = dtTinh.NewRow();
            dr[0] = ddlTinhThanh.SelectedValue;
            dr[1] = ddlTinhThanh.SelectedItem.Text;
            dtTinh.Rows.Add(dr);
            ViewState["dtTinhThuocVung"] = dtTinh;
            grvDsTinh.DataSource = ViewState["dtTinhThuocVung"];
            grvDsTinh.DataBind();
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        dt = new ClassExecute.ClassExecute();
        try
        {
            if (ViewState["dtTinhThuocVung"] != null)
            {

                        string Array = "";
                        DataTable dtTinhThuocVung = (DataTable)ViewState["dtTinhThuocVung"];
                        foreach (DataRow dr in dtTinhThuocVung.Rows)
                        {

                            Array = Array + dr[0].ToString() + ",";

                        }
                        bool kq = dt.ExecuteSQl_bool(str, CommandType.StoredProcedure, "[k_updateArea]", ref error,
                            new SqlParameter("@array", Array),
                            new SqlParameter("@AreaID", DropAreaID.SelectedValue));
                        if (kq)
                        {
                            ShowMessageBox("Bạn đã phân vùng địa lý thành công");
                        }
                        else
                        {
                            ShowMessageBox("Hệ thống đang bảo trì");
                        }
            }
            else
            {
                ShowMessageBox("Danh sách Tỉnh/Thành trong vùng địa lý rỗng.");
               
            }
        }
        catch (Exception ex)
        {

            string method = System.Reflection.MethodBase.GetCurrentMethod().Name;
            dt.WriteErrorLog(Server.MapPath(webapp4U.Globals.LogUrl()), ex.Message, method);
        }
    }
}
